﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Clinica_Frba.NewFolder8;
using System.Data.SqlClient;

namespace Clinica_Frba.Generar_Receta
{
    public partial class ViewRecetas : Form
    {
        protected InfoDeAfiliado afiliadoSeleccionado;
        private String idTurno = null;
        private String idReceta = null;
        private string[] bonosId = new string[0];

        public ViewRecetas(string idReceta)
        {
            InitializeComponent();
            this.idReceta = idReceta;
            this.idTurno = convertIdRecetaToIdTurno(idReceta);
            calcularAfiliadoPorIdTurno(idTurno);
            cargarBonosFarmacia();
            agregarMedicamentos();
        }

        private void cargarBonosFarmacia()
        {
            listBox1.DataSource = LoadBonoFarmaciaDataTable();
            listBox1.DisplayMember = "Fecha_Compra";
            listBox1.ValueMember = "Id";
        }

        public DataTable LoadBonoFarmaciaDataTable()
        {

            string comando = "select B.ID_BONO AS Id, B.Fecha_Compra as Fecha_Compra from BONO_FARMACIA B WHERE B.ID_RECETA = " + idReceta + " order by B.Fecha_Compra asc";
            System.Data.SqlClient.SqlConnection myConnection = new System.Data.SqlClient.SqlConnection(publico.ConnectionString);
            myConnection.Open();
            System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(comando, myConnection);
            DataTable dt = new DataTable();

            da.Fill(dt);

            return dt;
        }

        private void calcularAfiliadoPorIdTurno(string idTurno)
        {
            InfoDeAfiliado info = new InfoDeAfiliado();
            SqlConnection myConnection = new SqlConnection(publico.ConnectionString);
            myConnection.Open();
            SqlCommand consulta = new SqlCommand("SELECT top 1 * FROM AFILIADO af LEFT JOIN PLAN_MEDICO pm ON pm.ID_PLAN = af.ID_PLAN  WHERE af.ID_AFIL = (SELECT top 1 T.ID_AFIL FROM TURNO T WHERE T.ID_TURNO = '" + idTurno + "') ", myConnection);
            SqlDataReader executeCMD = consulta.ExecuteReader();
            executeCMD.Read();

            info.strAfiliadoID = executeCMD["ID_AFIL"].ToString();
            info.strCantidadDeFamiliaresDependientes = executeCMD["RELATIVOS_A_CARGO"].ToString();
            info.strNombre = executeCMD["Nombre"].ToString();
            info.strApellido = executeCMD["Apellido"].ToString();
            info.strEmail = executeCMD["mail"].ToString();
            info.strEstadoCivil = executeCMD["ESTADO_CIVIL"].ToString();
            info.strDireccion = executeCMD["Direccion"].ToString();
            info.strPlanMedico = executeCMD["descripcion"].ToString();
            info.strSexo = executeCMD["Sexo"].ToString();
            info.strTelefono = executeCMD["Telefono"].ToString();
            info.strNumeroDeDocumento = executeCMD["NRO_DOC"].ToString();
            info.strTipoDeDocumento = executeCMD["TIPO_DOC"].ToString();
            info.strFechaDeNacimiento = executeCMD["FECHA_NACIMIENTO"].ToString();


            executeCMD.Close();

            setAfiliadoSeleccionado(info);
        }

        private void agregarMedicamentos()
        {


            string itemIds = "";

            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                DataRowView item = (DataRowView)listBox1.Items[i];
                string itemId = item.Row["Id"].ToString();
                if (itemIds.Length == 0)
                {
                    itemIds = itemId;
                }
                else
                {
                    itemIds += ", " + itemId;
                }
            }
            itemIds = "(" + itemIds + ")";

            string command = "SELECT M.ID_MED, M.DESCRIPCION, MB.CANT_MED FROM MEDICAMENTO_BONO MB, MEDICAMENTO M WHERE M.ID_MED = MB.ID_MED AND ID_BONOF IN " + itemIds;

            SqlConnection myConnection = new SqlConnection(publico.ConnectionString);
            myConnection.Open();

            SqlCommand consulta = new SqlCommand(command, myConnection);
            SqlDataReader executeCMD = consulta.ExecuteReader();
            while (executeCMD.Read())
            {
                string idMedicamento = executeCMD["ID_MED"].ToString();
                string nombreMedicamento = executeCMD["DESCRIPCION"].ToString();
                string cantidadMedicamento = executeCMD["CANT_MED"].ToString();

                DataGridViewRow row = (DataGridViewRow)this.dataGridView1.RowTemplate.Clone();
                row.CreateCells(this.dataGridView1, new object[] { idMedicamento, nombreMedicamento, cantidadMedicamento, cantidadSeleccionadaEnLetras(cantidadMedicamento), "Ver" });

                this.dataGridView1.Rows.Add(row);
            }
        }

        private object cantidadSeleccionadaEnLetras(string p)
        {
            if (p != null)
            {
                if (p.Equals("1"))
                {
                    return "Uno";
                }
                if (p.Equals("2"))
                {
                    return "Dos";
                }
                if (p.Equals("3"))
                {
                    return "Tres";
                }
            }

            return "";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void AltaRecetas_Load(object sender, EventArgs e)
        {
            //this.dataGridView1.AutoGenerateDeleteButton = true;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex != -1)
            {
                dataGridView1.Rows.RemoveAt(e.RowIndex);
            }
        }
        #region FormBusquedaAfiliadoRecetaParent Members

        void setAfiliadoSeleccionado(InfoDeAfiliado info)
        {
            this.afiliadoSeleccionado = info;
            if (afiliadoSeleccionado != null)
            {
                this.textBox1.Text = afiliadoSeleccionado.strApellido + ", " + afiliadoSeleccionado.strNombre + " (Afiliado: " + afiliadoSeleccionado.strAfiliadoID + ")";
            }
            else
            {
                this.textBox1.Text = "";
            }
        }



        #endregion

        
        private static string convertIdRecetaToIdTurno(string idReceta)
        {
            string strQuery = "select R.ID_TURNO AS ID_TURNO from RECETA R WHERE R.ID_RECETA = " + idReceta;

            System.Data.SqlClient.SqlConnection myConnection = new System.Data.SqlClient.SqlConnection(publico.ConnectionString);
            myConnection.Open();
            System.Data.SqlClient.SqlCommand consulta = new System.Data.SqlClient.SqlCommand(strQuery, myConnection);
            //System.Data.SqlClient.SqlDataReader executeCMD = consulta.ExecuteReader();

            string idTurno = consulta.ExecuteScalar().ToString();

            return idTurno;
        }
    }
}
